package com.caibq.service.impl;

import com.caibq.annotation.PayCode;
import com.caibq.service.IPay;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.HashMap;
import java.util.Map;

/**
 * projectName: demoBox
 *
 * @author: caicai
 * time: 2024/1/11 10:32 周四
 * description:这种方式的code可以没有业务含义，可以是纯数字，只有不重复就行。
 */
@Service
public class PayService2  implements ApplicationListener<ContextRefreshedEvent> {

    private static Map<String, IPay> payMap = null;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();//获取应用上下文
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(PayCode.class);
        if (beansWithAnnotation!=null){
            payMap=new HashMap<>();
            beansWithAnnotation.forEach((key,value)->{
                String bizType = value.getClass().getAnnotation(PayCode.class).value();
                payMap.put(bizType, (IPay) value);
            });
        }
    }

    public void pay(String code) {
        payMap.get(code).pay();
    }



}























